<?php


namespace App\Admin\Override;

use App\Admin\Grid\Tools\CreateButton as NewCreate;
use App\Http\Logic\System\AdminUserLogic;
use App\Utils\Helper;
use Dcat\Admin\Admin;
use Dcat\Admin\Grid as Base;
use Dcat\Admin\Grid\Displayers\Actions;
use Dcat\Admin\Grid\Filter;
use Dcat\Admin\Grid\Tools\BatchActions;
use Illuminate\Support\Facades\Schema;
use App\Admin\Actions\BatchRestore;

class Grid extends Base
{
    public $editName = '';
    public $create_blank = false;
    public $minStyle = true;
    public function __construct($repository = null, \Closure $builder = null, $request = null)
    {
        parent::__construct($repository, $builder, $request);
        if (
            $this->model()->repository() &&
            Schema::hasColumn($this->model()->repository()->model()->getTable(), 'id')
        ) {
            $this->model()->orderBy('id', 'desc');
        }
        if(!Admin::user()->isAdministrator()){
            //数据权限
            if(
                isset($this->model()->repository()->model()->isAdminPermission)
                &&
                $this->model()->repository()->model()->isAdminPermission
                &&
                Admin::user()->cannot(Helper::resolvePermissionRouteName('all'))
            ){
                $Permission = $this->model()->repository()->model()->adminPermission??'manager_id';
                if(Admin::user()->can(Helper::resolvePermissionRouteName('department'))){
                    //能查看部门
//                    $userIds = AdminUserLogic::getDepartmentUserIdAll(Admin::user()->department_id);
                    $userIds = AdminUserLogic::getDepartmentUserId(Admin::user()->department_id);
                    $this->model()->whereIn($Permission,$userIds);
                }else{
                    //能查看自己
                    $this->model()->where($Permission,Admin::user()->id);
                }
            }
        }
        $this->showNumber();
        $this->paginate(10);
        $this->toolsWithOutline(false);
        $this->disableQuickEditButton()
            ->showEditButton()
            ->showCreateButton()
            ->showDeleteButton();
//        $this->minStyle();
    }
    /**
     * override
     * @param bool $val
     * @return $this|Grid
     */
    public function showNumber(bool $val = true)
    {
        if($val){
            $this->number(' ')->width(30);
        }else{
            $this->number(' ')->setAttributes(['style' => 'display:none'])->setHeaderAttributes(['style' => 'display:none']);
        }
        return $this;
    }
    /**
     * override
     * @param bool $val
     * @return $this|Grid
     */
    public function showQuickEditButton(bool $val = true)
    {
        $this->renderCreateButton();
        return $this->disableQuickEditButton(
            Admin::user()->cannot(Helper::resolvePermissionRouteName('update'))
        );
    }
    //新增跳一个新页面
    public function renderCreateButton()
    {
        if (! $this->options['create_button']) {
            return '';
        }
        if($this->create_blank){
            return (new NewCreate($this))->render();
        }else{
            return (new Base\Tools\CreateButton($this))->render();
        }

    }

    /**
     * override
     * @param bool $val
     * @return $this|Grid
     */
    public function showEditButton(bool $val = true)
    {
        return $this->disableEditButton(
            Admin::user()->cannot(Helper::resolvePermissionRouteName('update'))
        );
    }

    public function getEditName(){
        return $this->editName;
    }

    public function setEditName(string $title = ''){
       $this->editName = $title;
       return $this;
    }

    /**
     * override
     * @param bool $val
     * @return $this|Grid|null
     */
    public function showCreateButton(bool $val = true)
    {
        return $this->disableCreateButton(
            Admin::user()->cannot(Helper::resolvePermissionRouteName('store'))
        );
    }

    /**
     * @return Grid|null
     */
    public function showCreateButtonIsAdmin(){
        return $this->disableCreateButton(
            !Admin::user()->isAdministrator()
        );
    }
    public function showDeleteButton(bool $val = true)
    {
        return $this->disableDeleteButton(
            Admin::user()->cannot(Helper::resolvePermissionRouteName('destroy'))
        );
    }

    /**
     * @param string $modelClass
     * @param string|null $field
     * @return $this
     */
    public function useTrashedFilterAndRestoreAction(string $modelClass, string $field = null): Grid
    {
        if ($field && Maintenance::isNotMaintenance($field)) {
            return $this;
        }
        $this->filter->scope('trashed', trans('common.trashed'))->onlyTrashed();

        if ($this->isTrashedAction()) {
            $this->disableEditButton();
            $this->disableDeleteButton();

            $this->actions(function (Actions $actions) use ($modelClass) {
                $actions->append(new Restore($modelClass));
            });

            $this->batchActions(function (BatchActions $batchActions) use ($modelClass) {

                $batchActions->add(new BatchRestore($modelClass));
            });
        }

        return $this;
    }

    private function isTrashedAction(): bool
    {
        return $this->request->get('_scope_') == 'trashed';
    }

    public function newColumn($field = '', $label = '')
    {
        if ($field == 'id' && $label == '') {
            $label = trans('common.id');
        }
        return parent::newColumn($field, $label);
    }

    /**
     * @param string $field
     * @param array $actions
     * @return Grid
     */
    public function disableButtonOnMaintenance(
        string $field,
        array  $actions = ['store', 'update', 'destroy']
    ): Grid
    {
        if (Maintenance::isNotMaintenance($field)) {
            if (in_array('store', $actions)) {
                $this->disableCreateButton();
            }
            if (in_array('update', $actions)) {
                $this->disableEditButton();
                $this->disableQuickEditButton();
            }
            if (in_array('destroy', $actions)) {
                $this->disableDeleteButton();
                $this->disableBatchDelete();
            }
        }

        return $this;
    }

    /**
     * @return $this
     */
    public function withIdFilter(): Grid
    {
        $this->filter(function (Filter $filter) {
            $filter->expand(false);
            $filter->in('id');
        });

        return $this;
    }

    /**
     * @return $this
     */
    public function withNameFilter(): Grid
    {
        $this->filter(function (Filter $filter) {
            $filter->expand(false);
            $filter->like('name');
        });

        return $this;
    }

    /**
     * @param string|array|Closure $search
     * @param bool $auto
     * @return Grid
     */
    public function withQuickSearch($search = 'name', bool $auto = false): Grid
    {
        $this->quickSearch($search)->auto($auto);

        return $this;
    }
}
